package algocasts;

import java.util.Stack;

public class P141_ConvertBstToGreaterTree {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }

    private int dfs(TreeNode root, int sum) {
        if (root == null) return sum;
        int cur = dfs(root.right, sum);
        root.val += cur;
        return dfs(root.left, root.val);
    }

    // Time: O(n)  Space: O(n)
    public TreeNode convertBST(TreeNode root) {
        dfs(root, 0);
        return root;
    }

    // Time: O(n)  Space: O(n)
    public TreeNode convertBST_Iter(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        int sum = 0;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.right;
            }
            cur = stack.pop();
            cur.val += sum;
            sum = cur.val;
            cur = cur.left;
        }
        return root;
    }


}
